const express = require('express');
const router = express.Router();
const multer = require('multer');
const path = require('path');
const fs = require('fs');

// 目录准备
const uploadDir = path.join(__dirname, '../public/uploads');
const chunksDir = path.join(__dirname, '../public/chunks');

// 配置文件存储
const storage = multer.diskStorage({
  destination: function(req, file, cb) {
    cb(null, path.join(__dirname, '..', 'uploads/'));
  },
  filename: function(req, file, cb) {
    cb(null, Date.now() + '-' + file.originalname);
  }
});

// 创建multer实例
const upload = multer({
  storage: storage,
  limits: {
    fileSize: 50 * 1024 * 1024, // 50MB限制
  },
  fileFilter: function(req, file, cb) {
    // 允许的文件类型
    const allowedTypes = /jpeg|jpg|png|gif|mp4|avi|mov|pdf/;
    const extname = allowedTypes.test(path.extname(file.originalname).toLowerCase());
    const mimetype = allowedTypes.test(file.mimetype);

    if (extname && mimetype) {
      return cb(null, true);
    } else {
      cb(new Error('只允许上传图片、视频和PDF文件！'));
    }
  }
});

// 处理文件上传的路由
router.post('/file', async (req, res) => {
  try {
    // 检查uploads目录是否存在
    const fs = require('fs');
    const uploadsDir = path.join(__dirname, '..', 'uploads');
    if (!fs.existsSync(uploadsDir)) {
      console.log('uploads目录不存在，尝试创建...');
      fs.mkdirSync(uploadsDir, { recursive: true });
      console.log('uploads目录创建成功');
    }

    // 使用multer处理文件上传
    upload.array('files', 9)(req, res, async (err) => {
      if (err) {
        console.error('文件上传错误:', err);
        return res.status(400).json({
          message: '文件上传失败',
          error: err.message
        });
      }

      // 获取上传后的文件路径
      const fileUrls = req.files.map(file => {
        return '/uploads/' + file.filename;
      });

      res.status(200).json({
        message: '文件上传成功',
        fileUrls: fileUrls
      });
    });
  } catch (error) {
    console.error('服务器错误:', error);
    res.status(500).json({
      message: '文件上传失败',
      error: error.message
    });
  }
});



// 按文件类型创建子目录
const createTypeDirectories = () => {
    const types = ['images', 'videos', 'documents', 'audio', 'other'];
    types.forEach(type => {
        const typeDir = path.join(uploadDir, type);
        if (!fs.existsSync(typeDir)) {
            fs.mkdirSync(typeDir, { recursive: true });
        }
    });
};

// 初始化目录
[uploadDir, chunksDir].forEach(dir => {
    if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
});
createTypeDirectories();


// 获取文件类型目录
const getFileTypeDirectory = (fileType) => {
    if (!fileType) return 'other';
    const typeMap = {
        'IMAGE': 'images',
        'VIDEO': 'videos',
        'DOCUMENT': 'documents',
        'AUDIO': 'audio',
        'OTHER': 'other'
    };
    // 统一转大写
    return typeMap[fileType.toUpperCase()] || 'other';
};

// 分片存储
const chunkStorage = multer.diskStorage({
    destination: (req, file, cb) => cb(null, chunksDir),
    filename: (req, file, cb) => {
        const fileHash = req.body.fileHash;
        const index = req.body.index;
        cb(null, `${fileHash}-${index}`);
    }
});

const uploadChunk = multer({
    storage: chunkStorage,
    limits: { fileSize: 50 * 1024 * 1024 }
}).single('chunk');

// 分片上传
router.post('/chunk', (req, res) => {
    uploadChunk(req, res, function (err) {
        if (err) {
            return res.status(500).json({ code: 500, message: '分片上传失败', error: err.message });
        }
        if (!req.file) {
            return res.status(400).json({ code: 400, message: '没有上传文件' });
        }
        res.json({ code: 200, message: '分片上传成功', data: { filename: req.file.filename } });
    });
});

// 合并分片
router.post('/merge', async (req, res) => {
    try {
        const { fileHash, fileName, fileType } = req.body;
        
        const chunkFiles = fs.readdirSync(chunksDir)
            .filter(name => name.startsWith(fileHash))
            .sort((a, b) => parseInt(a.split('-')[1]) - parseInt(b.split('-')[1]));
            
        if (chunkFiles.length === 0) return res.status(400).json({ code: 400, message: '没有找到分片文件' });

        // 根据文件类型选择存储目录
        const typeDir = getFileTypeDirectory(fileType);
        const filePath = path.join(uploadDir, typeDir, fileName);
        const writeStream = fs.createWriteStream(filePath);

        for (const chunkFile of chunkFiles) {
            const chunkPath = path.join(chunksDir, chunkFile);
            writeStream.write(fs.readFileSync(chunkPath));
            fs.unlinkSync(chunkPath);
        }
        
        writeStream.end();
        writeStream.on('finish', () => res.json({ 
            code: 200, 
            message: '文件合并成功', 
            data: { 
                path: `/uploads/${typeDir}/${fileName}`,
                fileType: fileType
            } 
        }));
        writeStream.on('error', (error) => { throw error; });
    } catch (error) {
        res.status(500).json({ code: 500, message: '文件合并失败', error: error.message });
    }
});

// 验证分片
router.post('/verify', (req, res) => {
    try {
        const { fileHash } = req.body;
        const uploadedChunks = fs.readdirSync(chunksDir)
            .filter(name => name.startsWith(fileHash))
            .map(name => name.split('-')[1]);
        res.json({ code: 200, data: { uploadedChunks } });
    } catch (error) {
        res.status(500).json({ code: 500, message: '验证失败', error: error.message });
    }
});


module.exports = router;